import Vue from 'vue'
import Vuex from 'vuex'
import { getRecommendCourses } from '@/api/course'
import { getLatestMaterials } from '@/api/material'
import { getUpcomingExams } from '@/api/exam'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    token: localStorage.getItem('token') || '',
    userInfo: JSON.parse(localStorage.getItem('userInfo') || '{}'),
    courses: [],
    materials: [],
    exams: []
  },
  mutations: {
    SET_TOKEN(state, token) {
      state.token = token
      localStorage.setItem('token', token)
    },
    SET_USER_INFO(state, userInfo) {
      state.userInfo = userInfo
      localStorage.setItem('userInfo', JSON.stringify(userInfo))
    },
    CLEAR_USER_DATA(state) {
      state.token = ''
      state.userInfo = {}
      localStorage.removeItem('token')
      localStorage.removeItem('userInfo')
    },
    SET_COURSES(state, courses) {
      state.courses = courses
    },
    SET_MATERIALS(state, materials) {
      state.materials = materials
    },
    SET_EXAMS(state, exams) {
      state.exams = exams
    }
  },
  actions: {
    // 登录
    login({ commit }, userInfo) {
      return new Promise((resolve) => {
        // 模拟登录请求
        setTimeout(() => {
          const token = 'mock-token'
          const userInfo = { id: 1, username: 'student', name: '张三', avatar: 'https://picsum.photos/200' }
          commit('SET_TOKEN', token)
          commit('SET_USER_INFO', userInfo)
          resolve()
        }, 1000)
      })
    },
    // 退出登录
    logout({ commit }) {
      commit('CLEAR_USER_DATA')
    },
    // 获取课程列表
    getCourses({ commit }) {
      return new Promise((resolve, reject) => {
        getRecommendCourses()
          .then(response => {
            // 根据后端返回的数据结构进行处理
            let courses = []
            if (response && response.records) {
              // 使用后端返回的records数组
              courses = response.records.map(course => {
                // 将教师ID处理为前端需要的教师字段
                return {
                  ...course,
                  teacher: `教师${course.teacherId}`, // 暂时使用教师ID
                  studentCount: course.enrollCount // 将enrollCount映射为studentCount
                }
              })
            }
            commit('SET_COURSES', courses)
            resolve(courses)
          })
          .catch(error => {
            console.error('获取推荐课程失败:', error)
            reject(error)
          })
      })
    },
    // 获取学习资料
    getMaterials({ commit }) {
      return new Promise((resolve, reject) => {
        getLatestMaterials()
          .then(response => {
            // 处理后端返回的数据
            let materials = []
            if (response && response.records) {
              materials = response.records.map(material => {
                // 从文件URL解析文件类型
                const fileType = material.fileUrl ? material.fileUrl.split('.').pop().toLowerCase() : 'unknown'
                
                // 格式化文件大小和创建时间
                return {
                  ...material,
                  type: fileType,
                  size: material.fileSize ? formatFileSize(material.fileSize) : '未知大小',
                  createTime: formatDate(material.createTime)
                }
              })
            }
            commit('SET_MATERIALS', materials)
            resolve(materials)
          })
          .catch(error => {
            console.error('获取最新资料失败:', error)
            reject(error)
          })
      })
    },
    // 获取考试列表
    getExams({ commit }) {
      return new Promise((resolve, reject) => {
        getUpcomingExams({ limit: 4 }) // 限制返回4条数据
          .then(response => {
            let exams = []
            if (response && response.records) {
              exams = response.records.map(exam => {
                // 保存原始开始时间用于倒计时计算
                const rawStartTime = exam.startTime
                // 格式化日期和时间
                const startTime = formatDateTime(exam.startTime)
                
                // 确定考试状态
                let status = 'upcoming'
                const now = new Date()
                const examStart = new Date(exam.startTime)
                const examEnd = new Date(examStart.getTime() + exam.duration * 60000)
                
                if (now < examStart) {
                  status = 'upcoming' // 未开始
                } else if (now >= examStart && now <= examEnd) {
                  status = 'ongoing' // 进行中
                } else {
                  status = 'completed' // 已结束
                }
                
                return {
                  id: exam.id,
                  title: exam.title,
                  startTime: startTime,
                  rawStartTime: rawStartTime, // 添加原始时间
                  duration: exam.duration,
                  status: status,
                  subjectId: exam.subjectId,
                  subjectName: exam.subjectName
                }
              })
            }
            commit('SET_EXAMS', exams)
            resolve(exams)
          })
          .catch(error => {
            console.error('获取近期考试失败:', error)
            reject(error)
          })
      })
    }
  },
  getters: {
    isAuthenticated: state => !!state.token,
    userInfo: state => state.userInfo
  }
})

// 格式化文件大小
function formatFileSize(bytes) {
  if (!bytes || bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

// 格式化日期
function formatDate(dateStr) {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  return `${date.getFullYear()}-${padZero(date.getMonth() + 1)}-${padZero(date.getDate())}`
}

// 补零
function padZero(num) {
  return num < 10 ? '0' + num : num
}

// 格式化日期和时间
function formatDateTime(dateStr) {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  return `${date.getFullYear()}-${padZero(date.getMonth() + 1)}-${padZero(date.getDate())} ${padZero(date.getHours())}:${padZero(date.getMinutes())}`
} 